{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.01821127 0.24519181 0.73659691]\n",
      "[nan nan nan]\n",
      "[9.99954600e-01 4.53978686e-05 2.06106005e-09]\n",
      "[0.01821127 0.24519181 0.73659691]\n",
      "1.0\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\yzpang\\AppData\\Local\\Temp\\ipykernel_13932\\3678867871.py:17: RuntimeWarning: overflow encountered in exp\n",
      "  print(np.exp(a) / np.sum(np.exp(a)))\n",
      "C:\\Users\\yzpang\\AppData\\Local\\Temp\\ipykernel_13932\\3678867871.py:17: RuntimeWarning: invalid value encountered in divide\n",
      "  print(np.exp(a) / np.sum(np.exp(a)))\n"
     ]
    }
   ],
   "source": [
    "# softmax函数的实现\n",
    "\n",
    "import numpy as np\n",
    "\n",
    "def softmax(a):\n",
    "    c = np.max(a)\n",
    "    exp_a = np.exp(a - c)\n",
    "    sum_exp_a = np.sum(exp_a)\n",
    "    y = exp_a / sum_exp_a\n",
    "    return y\n",
    "\n",
    "a = np.array([0.3, 2.9, 4.0])\n",
    "print(softmax(a))\n",
    "\n",
    "# 数据溢出问题\n",
    "a = np.array([1010, 1000, 990])\n",
    "print(np.exp(a) / np.sum(np.exp(a)))\n",
    "# 解决方案\n",
    "c = np.max(a)\n",
    "print(np.exp(a - c) / np.sum(np.exp(a - c)))\n",
    "\n",
    "# 修改后的调用\n",
    "a = np.array([0.3, 2.9, 4.0])\n",
    "print(softmax(a))\n",
    "print(np.sum(softmax(a)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}